<template>
    <div>
      <!-- 添加商品 -->
      <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/GoodsList' }">商品列表</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 内容区 -->
      <el-card>
        <!-- 提示栏 -->
        <el-alert title="请添加商品信息" type="info" center show-icon> </el-alert>
        <!-- 步骤条 -->
        <el-steps :active="activeNumber-0">
          <el-step title="基本信息" icon="el-icon-edit" ></el-step>
          <el-step title="商品参数" icon="el-icon-document"></el-step>
          <el-step title="商品属性" icon="el-icon-tickets"></el-step>
          <el-step title="商品图片" icon="el-icon-picture"></el-step>
          <el-step title="商品内容" icon="el-icon-edit-outline"></el-step>
          <el-step title="完成" icon="el-icon-check"></el-step>
        </el-steps>
        <!-- tab标签 -->
        <!-- 整体的表格 -->
        <el-form :model="allGoodsForm" :rules="allGoodsRules" ref="allGoodsRef" label-width="100px" class="demo-ruleForm" label-position="top">
          <el-tabs :tab-position="'left'" v-model="activeNumber" :before-leave = 'checkTab' @tab-click="tabchick">
          <el-tab-pane label="基本信息" name ='0'>
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="allGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="allGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="allGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="allGoodsForm.goods_number" ></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                @change ='changeClass'
                :options="goodsClassData"
                  v-model = 'theId'
                :props="forClass"
                change-on-select
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name ='1'>
            <el-form-item :label="item.attr_name" 
             v-for ="(item,i) in onlydata" :key="i">

              <el-checkbox v-model="item.attr_vals"
              v-for = '(val,n) in item.attr_vals'
              :key="n"
               :label="val" border></el-checkbox>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name ='2'>
            <el-form-item :label="many.attr_name"
            v-for="(many,a) in manydata"
            :key="a"
             prop="many">
              <el-input v-model="many.attr_vals" ></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name ='3'>
            <el-upload
              class="upload-demo"
              :headers="headersobj"
              :on-success = 'upsuccess'
              action="http://www.ysqorz.top:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture">
              <el-button size="small" type="primary" >点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name ='4'>
            <!-- 文本编辑框 -->
            <quill-editor v-model="allGoodsForm.goods_introduce" />
            <div v-html="allGoodsForm.goods_introduce"></div>
            <el-button type="primary" @click="sureadd">确认添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
        </el-form>
      </el-card>
    </div>
</template>

<script>
export default {
    data() {
        return {
          activeNumber:'',
          allGoodsForm:{
            goods_name:'',
            goods_price:'',
            goods_cat:[],
            goods_weight:'',
            goods_number:'',
            pics:[],
            goods_introduce:'',
            attrs:[]
          },
          allGoodsRules:{
          goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' },],
          goods_price:[{ required: true, message: '请输入商品价格', trigger: 'blur' },],
          goods_weight:[{ required: true, message: '请输入商品重量', trigger: 'blur' },],  
          goods_number:[{ required: true, message: '请输入商品数量', trigger: 'blur' },]
            },
          goodsClassData:[],
          forClass:{
            value:'cat_id',
            label:'cat_name',
            children:'children'
          },
          theId:[],
          onlydata:[],
          manydata:[],
          fileList:[//图片数据
                  ],
          headersobj:{//在请求头中，设置token值
            Authorization:window.sessionStorage.getItem('token')
          },
          content:'',
        }
    },
    created(){
      
    },
    mounted() {
      this.goClassData()
    },
    methods: {
      async goClassData(){
        const {data:res} = await this.$http.get('categories')
        if(res.meta.status ==! 200) return this.$message.error('获取分类数据失败')
        // console.log(res);
        this.goodsClassData = res.data
      },
      //切换tab标签之前
      checkTab(activeName,oldActiveName){
        console.log(this.theId);
        if(this.activeNumber === '0' && this.theId.length <3){
          this.$message.error('请选择商品分类')
          return false}
          },
        //切换tab的时候
        async tabchick(){
          if(this.activeNumber ==='1'){
            const {data:res} = await this.$http.get(
              `categories/${this.theId[2]}/attributes`,
              {params:{ sel:"only"}})
            // console.log(res);
            res.data.forEach(item => {
              item.attr_vals = item.attr_vals.split(',')
            });
            if(res.meta.status ==!200) return this.$message.error('获取参数列表失败')
            this.onlydata = res.data
            }else if(this.activeNumber ==='2'){
              const {data:res} = await this.$http.get(
              `categories/${this.theId[2]}/attributes`,
              {params:{ sel:"many"}})
            // console.log(res);
            if(res.meta.status ==!200) return this.$message.error('获取参数列表失败')
            this.manydata = res.data
            }
        },
      //选择了选择框后
      changeClass(){
        if(this.theId.length < 3){
          this.$message.error('必须选择第三级分类')
          this.theId = []
          return
        }
      },
      //打开图片
      handlePreview(){

      },
      //移除图片
      handleRemove(file){
        // console.log(file);//获取当前移除的图片暂存路径
        const filepath = file.response.data.tmp_path
        //找到移除图片所在的索引位置
        const fileindex =this.allGoodsForm.pics.findIndex(x=>{
          x.pic === filepath})
        this.allGoodsForm.pics.splice(fileindex,1)
        console.log(this.allGoodsForm);
      },
      //上传成功事件
      upsuccess(data){
        console.log(data);
        const newpic = {pic:data.data.tmp_path}
        console.log(newpic);
        this.allGoodsForm.pics.push(newpic)
        console.log(this.allGoodsForm);
      },
      //确认添加
      sureadd(){
        this.$refs.allGoodsRef.validate(async (valid) => {
          if (!valid) return this.$message.error('请完善商品信息')
          this.allGoodsForm.goods_cat = this.theId.join(',')
          // console.log(this.theId);
          // console.log(this.allGoodsForm.goods_cat);
          this.onlydata.forEach(item =>{
            const attobj = {attr_id:item.attr_id,attr_value:item.attr_vals}
            this.allGoodsForm.attrs.push(attobj)
          })
          this.manydata.forEach(item =>{
            const attobj = {attr_id:item.attr_id,attr_value:item.attr_vals}
            this.allGoodsForm.attrs.push(attobj)
          })
          const {data:res} = await this.$http.post('goods',this.allGoodsForm)
          console.log(res);
          if(res.meta.status ==!200)return this.$message.error("创建商品信息失败")
          this.$message.success('创建商品信息成功')
          this.$router.push('/GoodsList')
        })
      }
   
    }
};
</script>

<style scoped>
.el-steps{
  margin-top: 20px;
  font-size: 12px;
}
.el-tabs{
  margin-top: 20px;
}
.el-button{
  margin-top: 20px;
}
</style>
